#!/usr/bin/python
"""
This program makes txt file for Circos plots
Use tab files as input: eg: GKIL.v7.tab
or Genbank file?



"""

import sys
import re

tabfile = open(sys.argv[1], "rU")
tfl = tabfile.readlines()

cogfile = open(sys.argv[2], "rU")
cfl = cogfile.readlines()

cogcat = re.compile('\[(.*)\]\t(\w+)\t.*')

cogdict = {
    'J' : 'vlgrey',
    'A' : 'grey',
    'K' : 'vvlgrey',
    'L' : 'vlred',
    'B' : 'vvlred',
    'D' : 'red',
    'Y' : 'vvlgreen',
    'V' : 'vlgreen',
    'T' : 'green',
    'M' : 'dgreen',
    'N' : 'dred',
    'Z' : 'vvlpurple',
    'W' : 'vlpurple',
    'U' : 'purple',
    'O' : 'vvlorange',
    'C' : 'vlorange',
    'G' : 'lorange',
    'E' : 'orange',
    'F' : 'vlyellow',
    'H' : 'lyellow',
    'I' : 'yellow',
    'P' : 'black',
    'Q' : 'vvdred',
    'R' : 'vvdblue',
    'S' : 'lblue',
}

cogcatdict = {}

for line in cfl:
    tmp = line.strip()
    if cogcat.match(tmp):
        pattern = cogcat.match(tmp)
        cogcatdict[pattern.group(2)] = pattern.group(1)[0]

cogfile.close()
tabfile.close()

cds_tracks = []
rna_tracks = []
oth_tracks = []

for line in tfl:
    l = line.split('\t')
    feat = l[0]
    ltag = l[1]
    start = l[2]
    stop = l[3]
    frame = l[4]
    gene = l[5]
    ecnum = l[7]
    cog = l[8]
    desc = l[10].rstrip()
    cogcolor = 'vvlblue'    

    if cog in cogcatdict:
        if cogcatdict[cog] != '-':
            cogcolor = cogdict[cogcatdict[cog]]

    if feat == 'CDS':
        if frame == '+':
            cds_tracks.append(('chr1', start, stop, frame, 'fill_color='+cogcolor))
        else:
            cds_tracks.append(('chr1', start, stop, frame, 'fill_color='+cogcolor))
    elif feat == 'rRNA':
        rna_tracks.append(('chr1', start, stop, frame, 'fill_color=vvdpurple'))
    elif feat == 'tRNA':
        rna_tracks.append(('chr1', start, stop, frame, 'fill_color=vvdred'))
    elif feat == 'repeat_region':
        oth_tracks.append(('chr1', start, stop, frame, 'fill_color=vvdorange'))

for i in cds_tracks:
    if i[3] == '+':
        print i[0], i[1], i[2], i[4]
for j in rna_tracks:
    if i[3] == '+':
        print j[0], j[1], j[2], j[4]
#for k in oth_tracks:
#    print k[0], k[1], k[2], k[4]

